package response

import (
	"github.com/gin-gonic/gin"
)

type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

const (
	ErrCodeOk          = 0
	ErrCodeParmResolve = 1001
	ErrCodeInternal    = 1002
	ErrCodeNotFound    = 1003
)

var codeMap = map[int]string{
	ErrCodeOk:          "正确",
	ErrCodeParmResolve: "参数解析错误",
	ErrCodeNotFound:    "资源未找到",
	ErrCodeInternal:    "服务器内部错误",
}

func response(ctx *gin.Context, code int, data any, msg string) {
	ctx.JSON(200, Response{
		Code: code,
		Msg:  msg,
		Data: data,
	})
}

func Ok(ctx *gin.Context, data any, msg string) {
	response(ctx, 0, data, msg)
}

func OkWithData(ctx *gin.Context, data any) {
	Ok(ctx, data, "success")
}

func OkWithMsg(ctx *gin.Context, msg string) {
	Ok(ctx, gin.H{}, msg)
}

func Fail(ctx *gin.Context, code int, data any, msg string) {
	response(ctx, code, data, msg)
}

func FailWithMsg(ctx *gin.Context, msg string) {
	Fail(ctx, 1003, nil, msg)
}

func FailWithCode(ctx *gin.Context, code int) {
	msg, ok := codeMap[code]
	if !ok {
		msg = "new error"
	}
	Fail(ctx, code, nil, msg)
}
